import React, { Component } from 'react';
import styled from 'styled-components';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import ContainerWithBottomLine from 'widget/ContainerWithBottomLine';
import RestService from 'service/RequestServices/RestService';
import EmptyPage from 'widget/EmptyPage';
import Loading from 'widget/Loading';
import QuestionItem from './QuestionItem';
import More from '../More';

const Root = styled.div`
  position: relative;
`;

const ListContainer = styled(ContainerWithBottomLine)`
  padding: 16px 20px;
`;

class QuestionList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      list: props.data.list,
      total: props.data.total
    };
    this.handleClickMore = this.handleClickMore.bind(this);
  }

  fetchData(offset) {
    const { id } = this.props;
    const limit = 10;

    RestService.fetchRestList('questions', limit, offset, `questionProfileID=${id}`)
      .then(message => {
        const list = message;
        this.state.loading = false;
        this.state.list = this.state.list.concat(list);
        this.setState(this.state);
      })
      .catch(err => {
        console.warn(err);
      });
  }

  fetchMore() {
    const { list } = this.state;
    const offset = list.length;
    this.fetchData(offset);
  }

  handleClickMore() {
    this.state.loading = true;
    this.fetchMore();
    this.setState(this.state);
  }

  render() {
    const { ...props } = this.props;
    const { loading, list, total } = this.state;

    const more = total - list.length;
    const hasMore = more > 0;

    return (
      <Root {...props} style={{ minHeight: list.length === 0 && 180 }}>
        {list.length === 0 && (
          <EmptyPage>
            <FormattedMessage id="nodata.question" />
          </EmptyPage>
        )}
        {list.map((item, index) => (
          <ListContainer key={item.id} bottomLine={index < total - 1}>
            <QuestionItem
              data={{
                id: item.id,
                title: item.title,
                time: item.createAt,
                answersCounts: item.answersCounts,
                followers: 0
              }}
            />
          </ListContainer>
        ))}
        {hasMore && (
          <ListContainer key="more">
            {!loading && <More onClick={this.handleClickMore}>View More Questions({more})</More>}
            {loading && <Loading />}
          </ListContainer>
        )}
      </Root>
    );
  }
}

QuestionList.propTypes = {
  id: PropTypes.number.isRequired,
  data: PropTypes.shape({
    total: PropTypes.number.isRequired,
    list: PropTypes.arrayOf(
      PropTypes.shape({
        id: PropTypes.number.isRequired
      })
    ).isRequired
  }).isRequired
};

export default QuestionList;
